<script lang="ts">
export default {
  name: "DeviceEditDialog"
}
</script>

<!--
 * @Description: 设备编辑对话框
 * @version:
 * @Author:
 * @Date: 2022-10-24 09:10:28
 * @LastEditors:
 * @LastEditTime: 2022-10-24 09:10:28
-->
<template>
  <!-- 对话框 -->
  <el-dialog :close-on-click-modal="false" :model-value="visible" :title="dataState.title" min-width="200px"
             @close="handleCancel">

    <!-- 数据表单 -->
    <el-form ref="dataFormRef" :model="dataState.formData" :rules="dataState.rules" label-width="80px">

      <el-form-item label="通道类型" prop="channelType">
        <el-select v-model="dataState.formData.channelType" :disabled="dataState.type==='update'" allow-create filterable placeholder="请选择"
                   @change="handleSelectChannelType">
          <el-option
            v-for="item in dataState.channelTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="配置参数" prop="paramJson">
        <el-input v-model="dataState.formData.paramJson" :autosize="{ minRows: 1, maxRows: 15 }"
                  type="textarea"/>
      </el-form-item>


      <el-form-item label="描述信息" prop="description">
        <el-input v-model="dataState.formData.description" :autosize="{ minRows: 1, maxRows: 100 }" type="textarea"/>
      </el-form-item>

    </el-form>

    <!-- 脚部：确认/取消按钮-->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </template>

  </el-dialog>
</template>

<script lang="ts" setup>
import {nextTick, onMounted, reactive, ref} from "vue";

import {ElForm, ElMessage} from "element-plus";
import {isEmpty, isNull} from "@/utils/fieldutil";
import {listChannelTypeList} from "@/api/channel";

const props = defineProps(['visible']);
const emit = defineEmits(['create', 'update', 'cancel']); //注意：这个是父组件<dict-type-edit>标签上的@close
const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致

/**
 * 对外声明接口：父页面可以调用它
 */
defineExpose({initEditData});

// 数据状态：定义
let dataState = reactive({
  // 类型：create/update
  type: 'create',
  title: '添加',

  formData: {
    templateName: '',
    channelType: '',
    paramJson: '{}',
    description: '',
  } as any,

  entity: {} as any,

  // 通道类型选项
  channelTypeOptions: [] as OptionType[],

  // 对话框的各控件输入规则
  rules: {
    templateName: [{required: true, message: '参数不能为空', trigger: 'blur'}],
    channelType: [{required: true, message: '参数不能为空', trigger: 'blur'}],
    paramJson: [{required: true, message: '参数不能为空', trigger: 'blur'}],
  },
});

function handleCancel() {
  emit('cancel', "");
}

function handleSelectChannelType(value: any) {
  dataState.formData.templateName = value;
}

function handleSubmit() {
  try {
    if (isEmpty(dataState.formData.paramJson)) {
      ElMessage.info('配置参数的格式，不是合法的JSON格式!');
      return;
    }
    if (!dataState.formData.paramJson.startsWith('{') || !dataState.formData.paramJson.endsWith('}')){
      ElMessage.info('配置参数的格式，不是合法的JSON格式!');
      return;
    }

    dataState.entity.templateName = dataState.formData.channelType;
    dataState.entity.templateParam.channelType = dataState.formData.channelType;
    dataState.entity.templateParam.param = JSON.parse(dataState.formData.paramJson);
  } catch (e) {
    ElMessage.info('配置参数的格式，不是合法的JSON格式!');
    return;
  }


  if (isNull(dataState.entity.extendParam)){
    dataState.entity.extendParam = {};
  }
  dataState.entity.extendParam.description = dataState.formData.description;



  if (dataState.type === 'create') {
    emit('create', dataState.entity);
  }
  if (dataState.type === 'update') {
    emit('update', dataState.entity);
  }
}

/**
 * 初始化对话框
 * @taskParam type 对话框类型
 * @taskParam entity 实体
 */
function initEditData(type: string, value: any) {
  if (type === 'create') {
    dataState.type = type;
    dataState.title = '新增配置';

    // value：父页面的entity

    let entity  = {
      compId: value.id,
      manufacturer: value.manufacturer,
      deviceType: value.deviceType,
      subsetName: value.subsetName,
      channelType: '',
      templateName: '',
      templateType: 'channel-param',
      templateParam: {} as any,
      extendParam: {} as any,
    };

    dataState.entity = entity;

    if (isEmpty(dataState.entity.templateParam.param)){
      dataState.formData.paramJson = JSON.stringify({}, null, 5);
    }else {
      dataState.formData.paramJson = JSON.stringify(dataState.entity.templateParam.param, null, 5);
    }
    dataState.formData.description = dataState.entity.extendParam.description;

    nextTick(() => {
      dataFormRef.value.resetFields();
    })
    return;
  }


  if (type === 'update') {
    dataState.type = type;
    dataState.title = '修改配置';

    // value：页面的entity
    dataState.entity = value;

    dataState.formData.templateName = dataState.entity.templateName;

    if (isEmpty(dataState.entity.templateParam.param)){
      dataState.formData.paramJson = JSON.stringify({}, null, 5);
    }else {
      dataState.formData.paramJson = JSON.stringify(dataState.entity.templateParam.param, null, 5);
    }
    dataState.formData.channelType = dataState.entity.templateParam.channelType;

    dataState.formData.description = dataState.entity.extendParam.description;

    return;
  }
}

/**
 * 响应页面安装：页面的初始化工作
 */
onMounted(() => {
  listChannelTypeList().then(({data}) => {
    for (let type of data) {
      dataState.channelTypeOptions.push({value: type, label: type} as OptionType);
    }
    if (data.length > 0 && isEmpty(dataState.formData.channelType)){
      dataState.formData.channelType = data[0];
    }
  });
});

</script>
